package com.example.myapplication.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.SupposeBackground;
import org.androidannotations.annotations.SupposeUiThread;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


@EActivity(R.layout.activity_thread_test)
public class ThreadTestActivity extends AppCompatActivity {

    @ViewById
    Button btn_A,btn_B,btn_C,btn_D;

    @ViewById
    TextView textView;

    @ViewById
    WebView webView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Click({R.id.btn_A,R.id.btn_B,R.id.btn_C,R.id.btn_D})
    public void clickButton(View view) {
        switch (view.getId()) {
            case R.id.btn_A:
                Log.d("@Click", "测试Background");
                networkRequest();
                break;
            case R.id.btn_B:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        setViews("UiThread测试：显示数据");
                    }
                }).start();
                break;
            case R.id.btn_C:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        supposeBackgroundNoUiThread();
                    }
                }).start();
                break;
            case R.id.btn_D:
                supposeUiThreadNoBackground();
                break;
        }
    }

    @AfterViews
    public void initViews() {
        textView.setText("显示请求返回的数据");
        // 使TextView能上下滑动
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());

//        webView.loadUrl("http://www.baidu.com");

        /**
         * 覆盖WebView，使其不默认打开浏览器访问URL
         */
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("http://www.baidu.com");
    }

    /**
     * 网络请求，耗时操作，需要在子线程中运行
     */
    @Background
//    @Background(id = "test01")     // 命名操作,可用BackgroundExecutor.cancelAll("test01", true) 取消对应任务线程
//    @Background(serial = "test")   // 串行运行线程
//    @Background(delay = 2000)      // 延迟操作，2s后开启线程
    public void networkRequest() {
        try {
            URL url = new URL("https://www.baidu.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
//            connection.setConnectTimeout(5000);
//            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int length = 0;
                StringBuffer stringBuffer = new StringBuffer();
                while ((length = inputStream.read(buffer)) != -1) {
                    stringBuffer.append(new String(buffer,0,length,"UTF-8"));
                }
                Log.d("@Backgroud", "请求返回的数据为："+ stringBuffer.toString());
                setViews(stringBuffer.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @UiThread
    public void setViews(String str) {
        textView.setText(str);
    }
    @SupposeBackground
    public void supposeBackgroundNoUiThread() {
        Log.d("@SupposeBackground", "当前方法在'子'线程中运行...");
        showToast("当前方法在'子'线程中运行...");
    }
    @SupposeUiThread
    public void supposeUiThreadNoBackground() {
        Log.d("@SupposeUiThread", "当前方法在'主'线程中运行...");
        showToast("当前方法在'主'线程中运行...");
    }

    @UiThread
    public void showToast(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }
}
